/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include "event_storage.h"
#include <sqlite3.h>
#include <mutex>
#include <string>
#include "utils_noncopyable.h"

namespace El {
namespace Event {

class SqliteStorage : public IStorage {
    DISALLOW_COPY_AND_MOVE(SqliteStorage);

public:
    SqliteStorage();
    ~SqliteStorage();

    bool init(const nlohmann::json &config) override;

    bool deinit() override;

    bool store(const nlohmann::json &event_data) override;

    std::vector<nlohmann::json> query(int64_t start_time, int64_t end_time, const std::string &event_type) override;

    int delete_events(int64_t start_time, int64_t end_time, const std::string &event_type) override;

    size_t count() const override;

private:
    void close_db();
    bool create_tables();
    bool prepare_statements();

private:
    sqlite3 *db_;
    sqlite3_stmt *insert_stmt_;
    sqlite3_stmt *query_stmt_;
    std::string db_path_;
    size_t max_events_;
    mutable std::mutex mutex_;
};

} // namespace Event
} // namespace El
